package com.yoo.ons.function.profile

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.yoo.module_base.utils.ImageDrawableUtil
import com.yoo.module_base.utils.PictureSelectTypeUtil
import com.yoo.module_base.utils.SaveDeviceUtil
import com.yoo.module_base.utils.ScreenUtils
import com.yoo.module_base.utils.StatusBarUtil
import com.yoo.module_base.utils.date.DateUtil
import com.yoo.module_base.utils.setOnClickCallback
import com.yoo.module_base.view.tag.TagModel
import com.yoo.module_res.R
import com.yoo.ons.ToastUtil
import com.yoo.ons.adapter.UserTOAdapter
import com.yoo.ons.base.BaseVMActivity
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.databinding.ActivityEditProfileBinding
import com.yoo.ons.dialog.PictureSelectTypePopup
import com.yoo.ons.dialog.UpdateAboutMePopup
import com.yoo.ons.dialog.UpdateBirthDatePopup
import com.yoo.ons.dialog.UpdateGenderAndWantPopup
import com.yoo.ons.dialog.UpdateHeightPopup
import com.yoo.ons.dialog.UpdateMyInterestsPopup
import com.yoo.ons.dialog.UpdateNickNamePopup
import com.yoo.ons.dialog.UpdateTOPopup
import com.yoo.ons.dialog.UpdateYouAcceptPopup
import com.yoo.ons.event.MessageEvent
import com.yoo.ons.event.UserInfoEvent
import com.yoo.ons.function.profile.viewmodel.EditProfileViewModel
import com.yoo.ons.listener.PictureManagerListener
import com.yoo.ons.model.PictureManagerModel
import com.yoo.ons.model.TurnOnsListModel
import com.yoo.ons.model.UserInfoModel
import com.yoo.ons.model.UserWantOrYouAcceptModel
import com.yoo.ons.util.UploadPhotoUtil
import com.yoo.ons.view.PictureManagerView
import org.greenrobot.eventbus.EventBus

class EditProfileActivity : BaseVMActivity<ActivityEditProfileBinding, EditProfileViewModel>(
    ActivityEditProfileBinding::inflate,
    EditProfileViewModel::class.java
) {


    //从meFragemnt传递数据过来
    private lateinit var serializableExtra: UserInfoModel
    private val genderList by lazy {
        arrayListOf(
            UserWantOrYouAcceptModel(0, getString(R.string.queer)),
            UserWantOrYouAcceptModel(1, getString(R.string.male)),
            UserWantOrYouAcceptModel(2, getString(R.string.female))
        )
    }

    override fun initView() {
        super.initView()
        binding.titleBar.setTitleText(getString(R.string.edit_profile))
        binding.titleBar.setTitleBarPadding(StatusBarUtil.getStatusBarHeight(this))
        binding.titleBar.setBackListener { finish() }
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        //从meFragemnt传递数据过来
        serializableExtra = intent.getSerializableExtra("model") as UserInfoModel

        //设置头像信息
        binding.pictureManagerView.setData(serializableExtra.imagesV2)
        binding.pictureManagerView.addImageClickListener(object : PictureManagerListener {
            override fun imageClick(isAdd: Boolean) {
                if (isAdd) {
                    //上传照片
                    PictureSelectTypePopup(this@EditProfileActivity,
                        object : PictureSelectTypePopup.SelectListener {
                            override fun onSelectAlbumsListener() {
                                PictureSelectTypeUtil.openAlbum(this@EditProfileActivity)
                            }

                            override fun onSelectCameraListener() {
                                PictureSelectTypeUtil.openCamera(this@EditProfileActivity)

                            }

                        }).showPopupWindow()
                } else {
                    deleteImage()
                }
            }

        })

        binding.txtNickName.text = serializableExtra.nickName
        //裁剪月份，拼接英文
        if (serializableExtra.birthday != null) {
            val month =
                serializableExtra.birthday.subSequence(0, serializableExtra.birthday.indexOf("/"))
            val birth = "${DateUtil.getMonths()[Integer.parseInt(month.toString())]}${
                serializableExtra.birthday.subSequence(
                    2,
                    serializableExtra.birthday.length
                )
            }".replace("/", "-")
            binding.txtDateBirth.text =
                birth
        } else {
            binding.txtDateBirth.text = serializableExtra.birthday
        }
        binding.txtMyHeight.text = serializableExtra.inchHeight ?: ""

        //设置性别
        binding.txtGender.text = ImageDrawableUtil().addIconsToText(
            this,
            when (serializableExtra.gender) {
                1 -> getString(R.string.male)
                2 -> getString(R.string.female)
                else -> getString(R.string.queer)
            }, ContextCompat.getDrawable(
                this, when (serializableExtra.gender) {
                    1 -> R.mipmap.img_gender_male
                    2 -> R.mipmap.img_gender_female
                    else -> R.mipmap.img_gender_unknown
                }
            )
        )
        //设置性向，将设置的性向选中
        genderList[serializableExtra.lookingFor].selected = 1
        binding.txtLookFor.text = ImageDrawableUtil().addIconsToText(
            this,
            when (serializableExtra.lookingFor) {
                1 -> getString(R.string.male)
                2 -> getString(R.string.female)
                else -> getString(R.string.queer)
            }, ContextCompat.getDrawable(
                this, when (serializableExtra.lookingFor) {
                    1 -> R.mipmap.img_gender_male
                    2 -> R.mipmap.img_gender_female
                    else -> R.mipmap.img_gender_unknown
                }
            )
        )
        //判断about me是否有值
        if (serializableExtra.aboutMe != null && serializableExtra.aboutMe != "") {
            binding.txtAboutMe.text = serializableExtra.aboutMe
            binding.txtAboutMe.setBackgroundResource(R.drawable.shape_solid_a92ea3_radius_12)
        }
        //判断interest是否有值
        if (!serializableExtra.interests.isNullOrEmpty()) {
            binding.txtEmptyInterest.isVisible = false
            binding.interestTagList.isVisible = true
            binding.interestTagList.setTags(serializableExtra.interests)
        }


        //判断i want是否为空
        if (!serializableExtra.userWant.isNullOrEmpty()) {
            //判断i want是否有选择
            val filter = serializableExtra.userWant!!.filter {
                it.selected == 1
            }
            //将i want选中的项赋值
            if (filter.isNotEmpty()) {
                binding.txtNowIWant.text = filter[0].value
            }
        }

        //判断youAccept是否为空
        if (!serializableExtra.youAccept.isNullOrEmpty()) {
            //判断youAccept是否有选择
            val filter = serializableExtra.youAccept!!.filter {
                it.selected == 1
            }
            setYouAccept(filter)
        }

        //根据PPV开关展示turn ons
        binding.tOContainer.isVisible=!SaveDeviceUtil.getPPVSwitch()
        if(binding.tOContainer.isVisible){
            val turnOnsList = serializableExtra.turnOnsList
            //根据t-o列表的值判断展示列表还是空文案
            if (turnOnsList.isNullOrEmpty()){
                binding.txtTOEmpty.isVisible=true
                binding.tOList.isVisible=false
            }else{
                binding.txtTOEmpty.isVisible=false
                binding.tOList.isVisible=true
                binding.tOList.layoutManager=GridLayoutManager(this,2)
                val userTOAdapter = UserTOAdapter(false)
                val selectTOList = turnOnsList.filter { it.selected == 1 } as ArrayList<TurnOnsListModel>
                userTOAdapter.addAll(selectTOList)
                binding.tOList.adapter=userTOAdapter

                binding.imgTOAdd.setOnClickCallback {
                    //重新选择TO
                    UpdateTOPopup(this, turnOnsList){
                        //保存TO
                        saveProfileInfo(turnOns = it){
                            //更新TO
                            userTOAdapter.getDataList().clear()
                            val selectTONewList = turnOnsList.filter { it1 -> it1.selected == 1 } as ArrayList<TurnOnsListModel>
                            userTOAdapter.addAll(selectTONewList)
                        }
                    }.showPopupWindow()
                }
            }
        }
    }

    /**
     * 设置you accept列表
     */
    private fun setYouAccept(filter: List<UserWantOrYouAcceptModel>) {
        //当全部未选中时，展示空样式
        binding.txtYouAccept.isVisible = filter.isEmpty()
        binding.txtYouAcceptList.isVisible = filter.isNotEmpty()
        //将i want选中的项赋值
        if (filter.isNotEmpty()) {
            //动态创建you accept列表
            binding.txtYouAcceptList.removeAllViews()
            for (i in filter.indices) {
                val textView = TextView(this)
                textView.text = filter[i].value
                textView.setPadding(
                    ScreenUtils.dip2px(this, 15f),
                    ScreenUtils.dip2px(this, 10f),
                    0,
                    ScreenUtils.dip2px(this, 10f)
                )
                textView.typeface =
                    ResourcesCompat.getFont(this, R.font.lexenddeca_regular)
                textView.setTextColor(Color.WHITE)
                textView.setBackgroundResource(R.drawable.shape_solid_a92ea3_radius_12)
                val layoutParam = ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                layoutParam.bottomMargin = ScreenUtils.dip2px(this, 5f)
                textView.layoutParams = layoutParam
                binding.txtYouAcceptList.addView(textView)
            }
        }
    }

    override fun initListener() {
        super.initListener()
        //修改昵称
        binding.nickNameContainer.setOnClickCallback {
            UpdateNickNamePopup(this@EditProfileActivity, binding.txtNickName.text.toString()) {
                saveProfileInfo(nickName = it) {
                    runOnUiThread {
                        binding.txtNickName.text = it
                    }
                }
            }.showPopupWindow()
        }
        //修改生日
        binding.dateOfBirthContainer.setOnClickCallback {
            UpdateBirthDatePopup(this, binding.txtDateBirth.text.toString()) {
                if (it != "") {
                    saveProfileInfo(birthday = DateUtil.replace(it)) {
                        runOnUiThread {
                            binding.txtDateBirth.text = it
                        }
                    }
                }
            }.showPopupWindow()
        }


        //修改性向
        binding.lookingForContainer.setOnClickCallback {
            UpdateGenderAndWantPopup(this, getString(R.string.looking_for), genderList) { value ->
                if(serializableExtra.lookingFor == value.code){
                    return@UpdateGenderAndWantPopup
                }
                saveProfileInfo(lookingFor = value.code) {
                    runOnUiThread {
                        EventBus.getDefault().post(MessageEvent(4,""))
                        //将性向全部置为未选择
                        for (item in genderList) {
                            item.selected = 0
                        }
                        //设置当前选择的性向
                        genderList[value.code].selected = 1
                        binding.txtLookFor.text = ImageDrawableUtil().addIconsToText(
                            this,
                            when (value.code) {
                                1 -> getString(R.string.male)
                                2 -> getString(R.string.female)
                                else -> getString(R.string.queer)
                            }, ContextCompat.getDrawable(
                                this, when (value.code) {
                                    1 -> R.mipmap.img_gender_male
                                    2 -> R.mipmap.img_gender_female
                                    else -> R.mipmap.img_gender_unknown
                                }
                            )
                        )
                    }
                }
            }.showPopupWindow()
        }

        //修改身高
        binding.myHeightContainer.setOnClickCallback {
            UpdateHeightPopup(this, binding.txtMyHeight.text.toString()) {
                if (it != "") {
                    saveProfileInfo(height = it) {
                        runOnUiThread {
                            binding.txtMyHeight.text = it
                        }
                    }
                }
            }.showPopupWindow()
        }
        //修改about me
        binding.imgModifyAboutMe.setOnClickCallback {
            UpdateAboutMePopup(this, binding.txtAboutMe.text.toString()) {
                saveProfileInfo(aboutMe = it) {
                    runOnUiThread {
                        binding.txtAboutMe.text = it
                    }
                }
            }.showPopupWindow()
        }

        //修改兴趣
        binding.imgInterestAdd.setOnClickCallback {
            mViewModel?.getUserInterests(object : HttpRequestListener<ArrayList<TagModel>>() {
                override fun addRequestParams(params: HashMap<String, Any>) {
                }

                override fun success(t: ArrayList<TagModel>?) {
                    t?.let {
                        val tagList = t
                        //如果已有选择的interests，赋值到interests列表中，初始化选择状态
                        if (!serializableExtra.interests.isNullOrEmpty()) {
                            repeat(tagList.size) {
                                for (i in 0 until serializableExtra.interests.size) {
                                    if (tagList[it].interest == serializableExtra.interests[i]) {
                                        tagList[it].check = true
                                        break
                                    }
                                }
                            }
                        }
                        UpdateMyInterestsPopup(
                            this@EditProfileActivity,
                            tagList
                        ) { datalist ->
                            val checkedTags: ArrayList<String> = ArrayList()
                            val checkedTagsBean: MutableList<TagModel> = ArrayList()
                            repeat(datalist.size) {
                                if (datalist[it].check) {
                                    checkedTags.add(datalist[it].interest)
                                    checkedTagsBean.add(datalist[it])
                                }
                            }
                            saveProfileInfo(interests = checkedTagsBean) {
                                runOnUiThread {
                                    binding.txtEmptyInterest.isVisible = checkedTags.isNullOrEmpty()
                                    binding.interestTagList.isVisible = !checkedTags.isNullOrEmpty()
                                    binding.interestTagList.setTags(checkedTags)
                                    serializableExtra.interests = checkedTags
                                }
                            }
                        }.showPopupWindow()
                    }

                }

            })
        }
        //修改i want
        binding.imgNowIWantSelect.setOnClickCallback {
            serializableExtra.userWant?.let { it1 ->
                UpdateGenderAndWantPopup(
                    this,
                    getString(R.string.now_i_want),
                    it1
                ) { value ->
                    saveProfileInfo(userWant = value.code) {
                        runOnUiThread {
                            binding.txtNowIWant.text = value.value
                        }
                    }
                }.showPopupWindow()
            }
        }
        //修改you accept
        binding.imgYouAcceptSelect.setOnClickCallback {
            serializableExtra.youAccept?.let { it1 ->
                UpdateYouAcceptPopup(
                    this,
                    it1
                ) { list ->
                    val codes = arrayListOf<Int>()
                    list.forEach {
                        if (it.selected == 1) {
                            codes.add(it.code)
                        }
                    }
                    saveProfileInfo(youAccept = codes) {
                        runOnUiThread {
                            val filter = list.filter {
                                it.selected == 1
                            }
                            setYouAccept(filter)
                        }
                    }
                }.showPopupWindow()
            }
        }

    }


    /**
     * 保存信息
     */
    fun saveProfileInfo(
        nickName: String = "",
        birthday: String = "",
        lookingFor: Int = -1,
        interests: MutableList<TagModel> = arrayListOf(),
        aboutMe: String = "",
        height: String = "",
        hideHeight: Boolean = false,
        userWant: Int = 0,
        youAccept: ArrayList<Int> = arrayListOf(),
        turnOns: ArrayList<TurnOnsListModel> = arrayListOf(),
        success: (() -> Unit?)? = null
    ) {
        mViewModel?.saveProfileInfo(object : HttpRequestListener<UserInfoModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                if (nickName != "") {
                    params["nickName"] = nickName
                }

                if (userWant != 0) {
                    params["userWant"] = userWant
                }
                if (youAccept.size > 0) {
                    params["youAccept"] = youAccept
                }

                if (birthday != "") {
                    params["birthday"] = birthday
                }
                if (lookingFor >= 0) {
                    params["lookingFor"] = lookingFor
                }

                if (interests.isNotEmpty()) {
                    val list = arrayListOf<Int>()
                    repeat(interests.size) {
                        list.add(interests[it].interestCode)
                    }
                    params["interests"] = list
                }

                if (aboutMe != "") {
                    params["aboutMe"] = aboutMe
                }
                if (height != "") {
                    if (height == "0") {
                        params["hideHeight"] = hideHeight
                    } else {
                        params["height"] = height
                    }
                }
                if (turnOns.isNotEmpty()) {
                    val list = arrayListOf<Int>()
                    repeat(turnOns.size) {
                        if (turnOns[it].selected == 1) {
                            list.add(turnOns[it].turnOnsCode)
                        }
                    }
                    params["turnOnsList"]= list
                }


            }

            override fun success(t: UserInfoModel?) {
                success?.invoke()
                val userInfoEvent = UserInfoEvent()
                if (nickName != "") {
                    userInfoEvent.nickName = nickName
                }


                if (userWant != 0) {
                    serializableExtra.userWant?.let {
                        for (item in it) {
                            item.selected = if (item.code == userWant) 1 else 0
                        }
                        userInfoEvent.userWant = it
                    }
                }
                if (youAccept.size > 0) {
                    serializableExtra.youAccept?.let {
                        for (item in it) {
                            item.selected = if (youAccept.contains(item.code)) 1 else 0
                        }
                        userInfoEvent.youAccept = it

                    }

                }

                if (birthday != "") {
                    userInfoEvent.birthday = birthday
                }
                if (lookingFor > 0) {
                    userInfoEvent.lookingFor = lookingFor
                }

                if (interests.isNotEmpty()) {
                    val list = arrayListOf<String>()
                    repeat(interests.size) {
                        list.add(interests[it].interest)
                    }
                    userInfoEvent.interests = list
                }

                if (aboutMe != "") {
                    userInfoEvent.aboutMe = aboutMe
                }
                if (height != "") {
                    if (height == "0") {
                        userInfoEvent.hideHeight = hideHeight
                    } else {
                        userInfoEvent.inchHeight = height
                    }
                }
                EventBus.getDefault().post(MessageEvent(1, userInfoEvent))
            }

        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val selectList = PictureSelector.obtainSelectorList(data)
                    addImage(selectList)
                }
            }
        }
    }

    private fun addImage(selectList: ArrayList<LocalMedia>?) {
        selectList?.forEach {
            val path = when {
                it.isCompressed -> {
                    it.compressPath
                }

                it.isCut -> {
                    it.cutPath
                }

                else -> {
                    it.realPath
                }
            }
            if (path.contains(".mp4", true) || it.mimeType.contains(
                    ".3gp",
                    true
                ) || it.mimeType.contains(".mov", true)
            ) {
                ToastUtil.showToast("pls upload photo.")
                return
            }
            val userPhotoBeans = binding.pictureManagerView.userImages
            val userPhotoBean = userPhotoBeans[binding.pictureManagerView.photoSelectPosition]
            val opType = if (TextUtils.isEmpty(userPhotoBean.imageUrl)) 1 else 2
            val imageCode = if (opType == 1) "" else {
                userPhotoBean.imageCode
            }
            showProgressDialog(this)
            UploadPhotoUtil.uploadPhoto(
                this,
                path,
                imageCode,
                object : UploadPhotoUtil.OnListener {
                    override fun onSuccess(successPath: String, imageCode: String) {
                        hideProgressDialog()
                        val opType = if (TextUtils.isEmpty(imageCode)) 1 else 2
                        changePhotoInfo(
                            if (opType == 2) imageCode else "",
                            successPath,
                            opType,
                            if (binding.pictureManagerView.photoSelectPosition == 0) 1 else 0
                        )
                    }

                    override fun fail() {
                        hideProgressDialog()
                        ToastUtil.showToast("upload error,pls try again")
                    }

                })
        }
    }

    /**
     * 保存照片
     */
    fun savePhoto(
        imageCode: String,
        imageUrl: String,
        path: String,
        opType: Int,
        pictureManagerView: PictureManagerView
    ) {
        val uploadPhotoList = pictureManagerView.userImages
        if (opType == 1) {//新增
            var lastPosition = 0
            for (i in 0 until uploadPhotoList.size) {
                if (uploadPhotoList[i].imageUrl == "") {
                    lastPosition = i
                    break
                }
            }
            uploadPhotoList[lastPosition].imageUrl = imageUrl
            uploadPhotoList[lastPosition].imageLoadUrl = path
            uploadPhotoList[lastPosition].imageCode = imageCode
            uploadPhotoList[lastPosition].loading = false
            pictureManagerView.userImages = uploadPhotoList
            pictureManagerView.updateItemImage(lastPosition)
        } else if (opType == 2) {//修改
            var lastPosition = 0
            for (i in 0 until uploadPhotoList.size) {
                if (uploadPhotoList[i].imageCode == imageCode) {
                    lastPosition = i
                    break
                }
            }
            uploadPhotoList[lastPosition].imageUrl = imageUrl
            uploadPhotoList[lastPosition].imageLoadUrl = path
            uploadPhotoList[lastPosition].imageCode = imageCode
            uploadPhotoList[lastPosition].loading = false
            pictureManagerView.userImages = uploadPhotoList
            pictureManagerView.updateItemImage(lastPosition)
        } else if (opType == 3) {//删除
            val position = pictureManagerView.photoSelectPosition
            uploadPhotoList.removeAt(position)
            pictureManagerView.setData(uploadPhotoList)
        }
        val userInfoEvent = UserInfoEvent()
        userInfoEvent.imagesV2=pictureManagerView.userImages
        userInfoEvent.avatarUrl=pictureManagerView.userImages[0].imageUrl
        EventBus.getDefault().post(MessageEvent(1, userInfoEvent))
    }

    /**
     * 删除照片
     */
    fun deleteImage() {
        val userPhotoList =
            binding.pictureManagerView.userImages[binding.pictureManagerView.photoSelectPosition]
        changePhotoInfo(
            userPhotoList.imageCode,
            userPhotoList.imageUrl,
            3,
            0
        )
    }


    /**
     * opType1-新增 2-修改 3-删除
     * avatarFlag 1-是 0-否
     */
    fun changePhotoInfo(
        imageCode: String,
        imageUrl: String,
        opType: Int,
        avatarFlag: Int
    ) {
        showProgressDialog(this)
        mViewModel?.getChangeImage(object : HttpRequestListener<PictureManagerModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["opType"] = opType
                params["imageCode"] = imageCode
                params["imageUrl"] = imageUrl
                params["avatarFlag"] = avatarFlag
                params["type"] = 1
            }

            override fun success(t: PictureManagerModel?) {
                t?.apply {
                    savePhoto(
                        t.imageCode,
                        t.imageUrl,
                        t.imageUrl,
                        opType, binding.pictureManagerView
                    )
                }


            }


            override fun endRequest() {
                super.endRequest()
                hideProgressDialog()
            }
        })
    }


    companion object {
        fun start(context: Context?, model: UserInfoModel) {
            val intent = Intent(context, EditProfileActivity::class.java)
            intent.putExtra("model", model)
            context?.startActivity(intent)
        }
    }
}